package GearCommands;

import Connections.Peer;
import Gear.Factory;
import Gear.Gear;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * Implementation of the user command copy.
 * Copy the specified file into gear path.
 *
 * @author Davi Mendes
 */
public class GearCommandCopy implements GearCommand {

    @Override
    public void execute(String[] args, Gear gear) {
        try {
            if (args.length < 2) throw new IllegalArgumentException("Too few arguments to copy command.");

            String fName = args[1].substring(args[1].lastIndexOf(FileSystems.getDefault().getSeparator()) + 1);

            if (Peer.getInstance().newFile(fName)) {
                Files.copy(FileSystems.getDefault().getPath(args[1]), FileSystems.getDefault().getPath(Factory.getInstance().getSettings().getGearPath().toString(), fName), StandardCopyOption.REPLACE_EXISTING);
                Peer.getInstance().sycronizeSharedFolder().send();
            } else {
                System.out.println("Error: file " + fName + " alreasy exists in the networks, try to download it!");
            }

        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException ex) {
            System.out.println("Error on copy operation.");
        }
    }

}
